package com.gcu.drivingschool.common.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 七牛云文件上传工具类
 *
 * @author zzr
 * @create 2024-05-10-22:08
 */
public class FileUtil {
    private static final String accessKey = "YEvhka78dI-At0zZZ5RsvxYCRPdkdYHHiroFA0Ah";
    private static final String secretKey = "905MX-anWXCd2Xzz21vum3dB-dykhmdCk34dtWDL";
    private static final String bucket = "driving-school";
    private static final String cdn = "http://sejizdow6.hn-bkt.clouddn.com/";

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    public static String upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //http://sd9v90rml.hn-bkt.clouddn.com/6b6fa5a6-d89c-4d75-8d94-d09718c39d4b.jpg
        String url = "";


        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);

        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        //上传
        uploadManager.put(file.getInputStream(), fileName, upToken, null, null);
        url = cdn + fileName;
        return url;

    }

    /**
     * 删除文件
     *
     * @param url
     */
    public static void del(String url) throws QiniuException {
        Configuration cfg = new Configuration(Region.region2());
        String fileName = url.substring(cdn.length());
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        bucketManager.delete(bucket, fileName);
    }
}
